package org.gaaidou.ptarmigan.springboot.core.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.bind.PropertySourcesPlaceholdersResolver;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySources;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.util.SystemPropertyUtils;

@Slf4j
public final class PropsUtil {


    public static <T> T getConfigByEnv(Environment environment, String prefix, Class<T> clazz) {
        try {
            PropertyPlaceholderHelper placeholderHelper = new PropertyPlaceholderHelper(SystemPropertyUtils.PLACEHOLDER_PREFIX,
                    SystemPropertyUtils.PLACEHOLDER_SUFFIX,
                    SystemPropertyUtils.VALUE_SEPARATOR, true);
            PropertySources sources = ((ConfigurableEnvironment) environment).getPropertySources();
            Binder bindObject = new Binder(ConfigurationPropertySources.get(environment), new PropertySourcesPlaceholdersResolver(sources, placeholderHelper));
            BindResult<T> bindResult = bindObject.bind(prefix, clazz);
            return bindResult.get();
        } catch (Exception e) {
            log.error("Occur exception from reading configuration file to object : {}", e.getMessage(), e);
            throw e;
        }
    }
}
